package com.gao.template;

import com.gao.util.MessageUtil;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.util.text.StringUtil;

import java.io.*;
import java.util.*;

public class TemplateProvider {

    public static final String TEMPLATE_PATH = "/template";
    public static final String PLUGIN_ID = "com.gao.wmstools.id";

    Map<String, Object> templateMap;
    String path = "";
    MessageUtil messageUtil = new MessageUtil();


    public TemplateProvider() {
        //this.templateMap = new HashMap<>();
        this.templateMap = new TreeMap<>(
                new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        // 升序
                        return o1.compareTo(o2);
                    }
                }
        );
    }

    public Object getTemplateMap(String tranFun) {
        return templateMap.get(tranFun);
    }

    public Map<String, Object> getTemplateMap() {
        return templateMap;
    }

    public void templateProd() {
        try {
            File[] files = getTemplateFile();
            for (File file: files) {
                String templateName = file.getName().substring(0, file.getName().lastIndexOf("."));
                templateMap.put(templateName, file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

    }

    public List getTranFunList() {
        List list = new ArrayList();
        Iterator iterator = templateMap.keySet().iterator();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }

        return list;
    }
    /**
     * 获取插件路径
     * @return
     */
    public String getPluginPath() {
        IdeaPluginDescriptor[] plugins = PluginManager.getPlugins();
        String strPath = null;
        for (IdeaPluginDescriptor plugin: plugins) {
            if (PLUGIN_ID.equals(plugin.getPluginId().getIdString())) {
                File path = plugin.getPath();
                String pathAbsolutePath = path.getAbsolutePath();
                strPath = path.getPath();
                System.out.println("pathAbsolutePath " + pathAbsolutePath);
                //xmlText1.setText(pathAbsolutePath + "," + path.getPath());
            }
        }
        System.out.println("path " + strPath);
        return strPath;
    }

    /**
     * 获取模板文件列表
     * 获取 jar 包外部的资源文件
     * @return
     */
    public File[] getTemplateFile(){
        path = getPluginPath();
        return new File(path+TEMPLATE_PATH).listFiles();
    }

    public void refreshTemplateFile(Map templateMap) {
        //templateProd();
        File[] files = getTemplateFile();
        for (File file: files) {
            String templateName = file.getName().substring(0, file.getName().lastIndexOf("."));
            templateMap.put(templateName, file);
        }
    }

    /**
     * 读取模板文件内容
     * @param tranFun 模板文件代码
     * @return
     */
    public String getFileContent(String tranFun) {
        FileInputStream fis = null;
        StringBuilder sb = new StringBuilder(1024);
        try {
            fis = new FileInputStream((File) templateMap.get(tranFun));
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            String line;
            System.out.println(br.lines().toString());
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 将发送数据保存为模板
     * @param templateCode 模板代码
     * @param templateData   发送的数据模板
     */
    public void saveAsTemplate(String templateCode, String templateData) {
        if (StringUtil.isEmpty(templateCode)) {
            messageUtil.alertMsg("接口代码不能为空！");
            return;
        }

        if (StringUtil.isEmpty(templateData)) {
            messageUtil.alertMsg("模板数据不能为空！");
            return;
        }
        String fileName = path + TEMPLATE_PATH + "/" + templateCode + ".txt";
        File file = new File(fileName);
        // 如果文件为不存在，则创建文件
        if (!file.exists()) {
            try {
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                messageUtil.errorMsg("模板创建失败！");
                return;
            }
        }

        // 写入内容到文件
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            bw.write(templateData);
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
            messageUtil.errorMsg("模板保存失败！");
            return;
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        messageUtil.successMsg("模板保存成功！");
    }

    /**
     * 删除模板
     * @param templateCode 模板代码
     */
    public void deleteTemplate(String templateCode) {
        if (StringUtil.isEmpty(templateCode)) {
            messageUtil.alertMsg("接口代码不能为空！");
            return;
        }
        String fileName = path + TEMPLATE_PATH + "/" + templateCode + ".txt";
        File file = new File(fileName);
        try {
            if (file.delete()) {
                messageUtil.successMsg("模板删除成功！");
            }
        } catch (Exception e) {
            messageUtil.successMsg("模板删除失败！");
        }

    }
}
